import router from '@router'
import { useMenuStore } from "@/store/useMenuStore";
import {RouteItem} from '@/interface/user/userRouters'
import clone from 'rfdc'
// 全局前置导航守卫
export const beforeEach = (to) => {

  // 菜单数据重构,动态添加路由
  // initRouter()
  if(to.path === '/login'){
    return
  }
  // 登录验证
  if(!localStorage.getItem('TOKEN')){
    return '/login'
  }
  // 动态路由
  initRouter()
  // router.addRoute( {path: '/dashboard', name: '仪表盘', component: ()=>import('@/views/home/index.vue')});
  // 匹配当前路由
  if (to.matched.length === 0){
    console.log(to.path);
    router.push(to.fullPath)
    return
  }
  return true;
}
/*
* 1.如何动态添加路由，通过router.addRoutes()方法
* 2.menu的数据进行重构，如：() => import('@/views/home/index.vue')
* 3
*
* */
interface Child{
  parentView: string;
  path: string;
  name: string;
  meta: any;
  redirect: string;
  children?: Child[] | null;
  component: any;
  id?: string | undefined;
  hidden?: boolean | undefined;
  alwaysShow?: boolean | undefined;
  query?: string | undefined;
}
// 1.动态路由
let isRouterInitialized = false; // 新增标志位
let initRouter = () => {
  if (isRouterInitialized) return; // 如果已初始化，直接返回
  isRouterInitialized = true;
  let menuStore:RouteItem[] = useMenuStore().menu;
  let menuRouter = filterRouter(menuStore);
  menuRouter = flatRoutes(menuRouter);
  menuRouter.forEach((item:any) => {
    router.addRoute(item.parentView == 'layout' ? 'layout' : '', item);
  });
}
// 2.把component 重构成 箭头函数的形式
let filterRouter = (menu: RouteItem[]): Child[] => {
  let routerArr: Child[] = [];
  let routerItem: Child = {} as Child;
  menu.forEach((item:any) => {

    routerItem = {
      parentView: item.parentView ? item.parentView : 'layout',
      path: item.path,
      name: item.name,
      meta: item.meta,
      redirect: item.redirect,
      children: item.children ? filterRouter(item.children) : null,
      component: loadComponent(item.component)
    }
    routerArr.push(routerItem);
  })
  return routerArr;
}
//3. 对于component的调整
const modules: Record<string, () => Promise<any>> = import.meta.glob('@renderer/views/**/*.vue');
const modulesMap: Record<string, () => Promise<any>> = {};//4. 根据modulesMap[key]返回对应的value值
Object.keys(modules).forEach((key) => {
  const componentName = key.replace('/src/views', '')
    .replace('.vue', '').replace('/index', '')
    .replace('/', '');
  if (key.includes('index')){
    modulesMap[`${componentName}/index`] = modules[key];
  }
    modulesMap[componentName] = modules[key];

})
//4. 根据modulesMap[key]返回对应的value值
const loadComponent = (component: string | null): (() => Promise<any>) | undefined => {
  if (component) {
    return modulesMap[component];
  }
  return;
};
//5. 路由扁平化
const flatRoutes = (routes: Child[], breadcrumb: Child[] = []): Child[] => {
  let res: Child[] = [];
  //深度复制对象，并处理循环引用
  const cloneRoutes  = clone()(routes);
  cloneRoutes.forEach((route: Child) => {
    const tmp = { ...route };
    if (tmp.children) {
      let childrenBreadcrumb: Child[] = [...breadcrumb];
      childrenBreadcrumb.push(route);
      let tmpRoute = { ...route };
      tmpRoute.meta.breadcrumb = childrenBreadcrumb;
      delete tmpRoute.children;
      res.push(tmpRoute);
      let childrenRoutes = flatRoutes(tmp.children, childrenBreadcrumb);
      childrenRoutes.map((item) => {
        res.push(item);
      });
    } else {
      let tmpBreadcrumb = [...breadcrumb];
      tmp.meta.breadcrumb = tmpBreadcrumb;
      tmpBreadcrumb.push(tmp);
      res.push(tmp);
    }
  });
  return res;
};
// 全局后置导航守卫
export const afterEach = () => {
  console.log('全局后置导航守卫')
}
